package com.zh.zuul.filter;
import com.alibaba.fastjson.JSON;
import com.zh.common.util.OkHttpClientUtil;
import com.zh.common.constans.AuthConstant;
import com.zh.common.entity.JSONResult;
import com.zh.common.entity.Oauth;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import rx.Observable;
import rx.subjects.Subject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;


/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * @Description: 拦截token信息，检查是否有效
 * @Author: Li.HuiNeng
 * @Create in: 2020-01-14 10:54
 * @Version: 1.0.1*/


//@Component
public class tokenFilter extends ZuulFilter {

    @Autowired
    private RedisTemplate redisTemplate;

    private static final int TOKEN_ORDER = 20;

    private Logger log = LoggerFactory.getLogger(tokenFilter.class);

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return TOKEN_ORDER;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        HttpServletResponse response = context.getResponse();
        //向header中添加鉴权令牌
        RequestContext requestContext = RequestContext.getCurrentContext();
        //获取header
        String authorization = request.getHeader("Authorization");
        String[] paths = {
                "/auth/login/",
                "/auth/oauth/check_token",
                "/auth/authClient/refreshToken",
                "/risk/call",
                "/auth/authManage/",
        };
        for (int i = 0; i < paths.length; i++) {
            // 接口放行
            if (request.getServletPath().contains(paths[i])) return null;
        }
        if (authorization != null) {
            requestContext.addZuulRequestHeader("Authorization", authorization);
            String token = authorization.substring(7);
            try {
                // 异步检查token
                String jsonString = OkHttpClientUtil.getInstance().sendGetRequest(AuthConstant.URL_OAUTH_CHECK+"?token="+token);
                HashMap jsonMap = JSON.parseObject(jsonString, HashMap.class);
                Boolean b = (Boolean) jsonMap.get("active");
                if (Objects.isNull(b)) {
                    response.setContentType("text/html;charset=utf-8");
                    context.setSendZuulResponse(false);
                    context.setResponseStatusCode(202);
                    JSONResult jsonResult = new JSONResult();
                    jsonResult.setSuccess(false);
                    jsonResult.setMessage(AuthConstant.TOKEN_INVALID_MSG);
                    context.getResponse().getWriter().print(JSON.toJSONString(jsonResult));
                    context.getResponse().getWriter().flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
